//
//  PlayerTool.m
//  MusicPlay
//
//  Created by lanou3g on 16/6/20.
//  Copyright © 2016年 xufeng. All rights reserved.
//

#import "FXXPlayerTool.h"


@interface FXXPlayerTool()

//
@property (nonatomic, strong) AVPlayerItem *currentItem;
//
@property (nonatomic, strong) NSTimer *timer;
@end

@implementation FXXPlayerTool
single_implementation(FXXPlayerTool)

- (instancetype)init
{
    self = [super init];
    if (self) {
        //初始化player
        self.player = [[AVPlayer alloc] init];
        //设置音量
        self.player.volume = 0.5;
        //监听播放结束通知
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playerEnd) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    }
    return self;
}
//播放结束走的通知
- (void)playerEnd {
    if (self.delegate && [self.delegate respondsToSelector:@selector(playendOfUrl:)]) {
        //播放结束通知代理
        [self.delegate playendOfUrl:self.musicUrl];
    }
}

//设置url 切换歌曲
- (void)setMusicUrl:(NSURL *)musicUrl {
    
    _musicUrl = musicUrl;
    //如果有item,移除通知
    if (self.currentItem) {
        [self.currentItem removeObserver:self forKeyPath:@"status"];
        [self.currentItem removeObserver:self forKeyPath:@"loadedTimeRanges"];
        [self.currentItem removeObserver:self forKeyPath:@"playbackBufferEmpty"];
        [self.currentItem removeObserver:self forKeyPath:@"playbackBufferFull"];
    }
    AVPlayerItem *item = [[AVPlayerItem alloc] initWithURL:musicUrl];
    self.currentItem = item;
    //监听item属性
    [item addObserver:self forKeyPath:@"status" options:(NSKeyValueObservingOptionNew) context:nil];
    [item addObserver:self forKeyPath:@"loadedTimeRanges" options:(NSKeyValueObservingOptionNew) context:nil];
    //缓冲空了,没有可以播放的了
    [item addObserver:self forKeyPath:@"playbackBufferEmpty" options:(NSKeyValueObservingOptionNew) context:nil];
    //缓冲出数据,可以正常播放
    [item addObserver:self forKeyPath:@"playbackBufferFull" options:(NSKeyValueObservingOptionNew) context:nil];
    //播放
    [self.player replaceCurrentItemWithPlayerItem:item];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    //是否可以播放
    if ([keyPath isEqualToString:@"status"]) {
        NSInteger status = [change[@"new"] integerValue];
        switch (status) {
            case AVPlayerStatusReadyToPlay: {
                //播放
                [self play];
                //开始播放的时候回调
                if (self.delegate && [self.delegate respondsToSelector:@selector(startPlayOfUrl:)]) {
                    [self.delegate startPlayOfUrl:self.musicUrl];
                }
                break;
            }
            case AVPlayerStatusFailed: {
                
                break;
            }
            case AVPlayerStatusUnknown: {
                
                break;
            }
            default:
                break;
        }
    } else if ([keyPath isEqualToString:@"loadedTimeRanges"]) {//播放进度
    
    } else if ([keyPath isEqualToString:@"playbackBufferEmpty"]) {//缓冲空了,播放暂停了
    
    } else if ([keyPath isEqualToString:@"playbackBufferFull"]) {//缓冲数据下来了,可以播放了
        
    }
}

//播放
- (void)play {
    [self.player play];
    if (self.timer) {//防止两次点击播放timer重复
        return;
    }
    //开启定时器
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
    self.timer = timer;
    //放到主循环
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
}

- (void)timerAction {
    //当前是否播放
    if (self.player.rate != 1) {
        return;
    }
    //把当前的播放时间回调回去
    if (self.delegate && [self.delegate respondsToSelector:@selector(getcurrentTime:totalTime:)]) {
        //获取当前播放时间
        CGFloat time = CMTimeGetSeconds(self.currentItem.currentTime);
        CGFloat totalTime = CMTimeGetSeconds(self.currentItem.duration);
        [self.delegate getcurrentTime:time totalTime:totalTime];
    }
}

//暂停
- (void)pause {
    [self.player pause];
    //销毁定时器
    [self.timer invalidate];
    self.timer = nil;
}

//设置音量
- (void)setVolumeSlider:(CGFloat)volumeSlider {
    self.player.volume = volumeSlider;
}

//获取音量
- (CGFloat)volumeSlider {
    return self.player.volume;
}

//设置当前时间播放
- (void)seekToTime:(NSInteger)time {
    //暂停
    [self pause];
    //设置到什么地方
    [self.player seekToTime:CMTimeMakeWithSeconds(time, self.currentItem.currentTime.timescale) completionHandler:^(BOOL finished) {
        [self play];
    }];
}

//是否正在播放
- (BOOL)isPlaying {
    if (self.player.rate == 1) {
        return YES;
    } else {
        return NO;
    }
}



@end
